<?php ob_start();
session_start(); // on relaye la session 
if(isset($_SESSION["is_registered"]) && $_SESSION["is_registered"] == "registered"){
		$enregistrer = $_SESSION["is_registered"];
}else{
	header("location:../../../menu.php"); // redirection en cas d'echec
}
require_once('../../../Connections/microassur.php');
require_once('../../../utils/fonctions.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1"))
$bool=verifLibelle1('Code_unite') && verifLibelle('Nom_unite') &&  verifLibelle('Identifiant_region') && verifLibelle('Identifiant_region') && verifLibelle('Identifiant_utilisateur') ;

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1") && $bool && !existeChamp($database_microassur, $microassur,'unite','Code_unite',@$_POST['Code_unite'])) {
  $insertSQL = sprintf("INSERT INTO unite (Identifiant_unite, Code_unite, Nom_unite, Etat_unite, Identifiant_utilisateur, Identifiant_region) VALUES (%s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['Identifiant_unite'], "int"),
                       GetSQLValueString($_POST['Code_unite'], "text"),
                       GetSQLValueString($_POST['Nom_unite'], "text"),
                       GetSQLValueString($_POST['Etat_unite'], "text"),
                       GetSQLValueString($_POST['Identifiant_utilisateur'], "int"),
                       GetSQLValueString($_POST['Identifiant_region'], "int"));

  mysql_select_db($database_microassur, $microassur);
  mysql_query("START TRANSACTION");
  $Result1 = mysql_query($insertSQL, $microassur) or die(mysql_error());

  if($Result1){mysql_query("commit"); header("location:index.php?ajout=success");}

else {mysql_query("rollback");$message=colorer("Contacter la DSI, erreur création unité","false") ;}

}
elseif(isset($_POST["MM_insert"])&& !$bool) {

if(empty($_POST['Code_unite'])) $message=colorer("Vous devez saisir le code","false");
elseif(!verifLibelle1('Code_unite')) $message=colorer("Le code saisi comporte des caractères spéciaux interdits","false");

elseif(empty($_POST['Nom_unite'])) $message=colorer("Vous devez saisir le nom ","false");
elseif(!verifLibelle('Nom_unite')) $message=colorer("Le nom saisi comporte des caractères spéciaux interdits ","false");
else
//$message=colorer("Erreur: Au moins un champ est vide ou valeur incorrecte","false");
$message="";

}

elseif(isset($_POST["MM_insert"]) && existeChamp($database_microassur, $microassur,'unite','Code_unite',@$_POST['Code_unite']))
$message=colorer("Cette unité existe déjà","false") ;

/* Liste des utilisateurs directeur d'unité */ /* Modif Thia */

mysql_select_db($database_microassur, $microassur);
$query_rs_r = 'SELECT * FROM fonction WHERE upper(Libelle_fonction) LIKE "%UNIT%" ';
$rs_r = mysql_query($query_rs_r, $microassur) or die(mysql_error());
$row_rs_r = mysql_fetch_assoc($rs_r);
if(empty($row_rs_r) || !$row_rs_r) $row_rs_r['Identifiant_fonction'] = 0;
$totalRows_rs_r = mysql_num_rows($rs_r);

mysql_select_db($database_microassur, $microassur);
$query_rs = sprintf("SELECT * FROM unite WHERE Etat_unite = 'A'");
$rs = mysql_query($query_rs, $microassur) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);
$totalRows_rs = mysql_num_rows($rs);

mysql_select_db($database_microassur, $microassur);
$query_rs_reg = "SELECT * FROM unite";
$rs_reg = mysql_query($query_rs_reg, $microassur) or die(mysql_error());
$row_rs_reg = mysql_fetch_assoc($rs_reg);
$totalRows_rs_reg = mysql_num_rows($rs_reg);

mysql_select_db($database_microassur, $microassur);
$query_rs_user = 'SELECT * FROM utilisateur WHERE Identifiant_fonction ='.$row_rs_r['Identifiant_fonction']; /* modif Thia */
$rs_user = mysql_query($query_rs_user, $microassur) or die(mysql_error());
$row_rs_user = mysql_fetch_assoc($rs_user);
$totalRows_rs_user = mysql_num_rows($rs_user);

?>
<?php  if(isset($_GET['ajout']) && $_GET['ajout']='success')$message=colorer("L'unité est créée","true"); ?>
<?php if(isset($_GET['supp']) && $_GET['supp']=='err') $message=colorer("Contacter la DSI, erreur suppression unité","false"); ?>
<?php if(isset($_GET['mod']) && $_GET['mod']=='success') $message=colorer("La modification de l'unité est prise en compte","true"); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=8" />
			<title><?php echo $titleGen ?></title>
			<link rel="stylesheet" type="text/css" href="../../../css/main.css" />
            <link rel="stylesheet" type="text/css" href="list.css" />
			<!--[if IE 7]>
            	<link rel="stylesheet" type="text/css" href="../../../css/ie7.css" />
            	<link rel="stylesheet" type="text/css" href="form_ie7.css" />
            <![endif]-->
	</head>
<body>
			<div id="sf_menu1">
				<h3>Administration</h3>
				<?php
					if(isset($message))
						echo $message;
					$nommodule="Unité";
					$nommodule2="Liste des unités";
					$nom_module_saisie="Ecran saisie";
					?>
			</div>
			<div class="cleared"></div>
		<div class="corps1">
			<!--/***************************************/-->
			
			<div class="imgleft"></div>
			<div class="imgmiddle">
			<div class="btn"><span class="btnleft"></span><span class="btnmiddle"><h5><?php echo $nommodule; ?></h5></span><span class="btnright"></span></div>
			<div class="btn1"><span class="btnleft"></span><span class="btnmiddle"><h5><?php echo $nommodule2; ?></h5></span><span class="btnright"></span></div>
			<div class="cleared"></div>
                <table class="tab_list bordh">
                  <tr id="niv1">
                    <td class="col1">CODE</td>							
                    <td class="col2">NOM</td>
                    <td class="col2">NOM DIRIGEANT UNITE</td>
                    <td>REGION</td>
                  </tr>
                </table>
				<div class="content_table">
					<table class="tab_list">
						  <?php 
						mysql_select_db($database_microassur, $microassur);
						$query_rs_reg1 = "SELECT * FROM region";
						$rs_reg1 = mysql_query($query_rs_reg1, $microassur) or die(mysql_error());
						$row_rs_reg1 = mysql_fetch_assoc($rs_reg1);
						$totalRows_rs_reg1 = mysql_num_rows($rs_reg1);
						
						  $i=1;  if ($totalRows_rs_reg > 0) {
						  do {
						  $colname1_rs_reg_nom = "-1";
						if (isset($row_rs['Identifiant_region'])) {
						  $colname1_rs_reg_nom = $row_rs_reg['Identifiant_region'];
						}
						mysql_select_db($database_microassur, $microassur);
						$query_rs_reg_nom = sprintf("SELECT * FROM region WHERE Identifiant_region = %s", GetSQLValueString($colname1_rs_reg_nom, "text"));
						$rs_reg_nom = mysql_query($query_rs_reg_nom, $microassur) or die(mysql_error());
						$row_rs_reg_nom = mysql_fetch_assoc($rs_reg_nom);
						$totalRows_rs_reg_nom = mysql_num_rows($rs_reg_nom);

						  $colname_rs_user_code = "-1";
						if (isset($row_rs['Identifiant_utilisateur']
						)) {
						  $colname_rs_user_code = $row_rs['Identifiant_utilisateur'];
						}
						$colname_rs_user_code = "-1";
						if (isset($row_rs_reg['Identifiant_utilisateur'])) {
						  $colname_rs_user_code = $row_rs_reg['Identifiant_utilisateur'];
						}
						
						mysql_select_db($database_microassur, $microassur);
						$query_rs_user_code = sprintf("SELECT * FROM utilisateur WHERE Identifiant_utilisateur = %s", GetSQLValueString($colname_rs_user_code, "text"));
						$rs_user_code = mysql_query($query_rs_user_code, $microassur) or die(mysql_error());
						$row_rs_user_code = mysql_fetch_assoc($rs_user_code);
						$totalRows_rs_user_code = mysql_num_rows($rs_user_code);

						  ?>
							<?php // Show if recordset not empty ?>
							  <tr <?php if($i%2==0) echo 'class="colorligne"'; ?> >
								<td class="col1"><a href="modunite.php?Identifiant_unite=<?php echo $row_rs_reg['Identifiant_unite']; ?>"><?php echo $row_rs_reg['Code_unite']; ?></a></td>
								<td class="col2"><a href="modunite.php?Identifiant_unite=<?php echo $row_rs_reg['Identifiant_unite']; ?>"><?php echo tronque($row_rs_reg['Nom_unite'],20); ?></a></td>
								<td class="col2"><a href="modunite.php?Identifiant_unite=<?php echo $row_rs_reg['Identifiant_unite']; ?>"><?php echo tronque($row_rs_user_code['Prenom_utilisateur'],20); ?> <?php echo $row_rs_user_code['Nom_utilisateur']; ?></a></td>
								<td><a href="modunite.php?Identifiant_unite=<?php echo $row_rs_reg['Identifiant_unite']; ?>"><?php echo tronque($row_rs_reg_nom['Nom_region'],21); ?></a></td>
							  </tr>
							  <?php  // Show if recordset not empty ?>
							<?php $i++; } while ($row_rs_reg = mysql_fetch_assoc($rs_reg)); mysql_free_result($rs_user_code); mysql_free_result($rs_reg_nom); }?>
						</table>
						</div>
					</div>
					<div class="imgright"></div>
				<div class="cleared"></div>
				<!--/***************************************/-->
				<div id="br"></div>
				
						<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
			<div class="imgleft"></div>
			<div class="imgmiddle">
				<div class="btn"><span class="btnleft"></span><span class="btnmiddle"><h5><?php echo $nommodule; ?></h5></span><span class="btnright"></span></div>
				<div class="btn1"><span class="btnleft"></span><span class="btnmiddle"><h5><?php echo $nom_module_saisie; ?></h5></span><span class="btnright"></span></div>
					<div class="formulaire">
							<table class="tabform">
								<tr>
								  <td>CODE</td>
								  <td><input class="resize_1" type="text" maxlength="5" name="Code_unite" value="<?php if(isset($_POST['Code_unite']))echo remind_text('Code_unite');?>" size="32" /></td>
							</tr>
							<tr>
							  <td>NOM </td>
							  <td><input name="Nom_unite" type="text" maxlength="30" value="<?php if(isset($_POST['Nom_unite']))echo remind_text('Nom_unite');?>" size="40" />      </td>
							</tr>
							<tr>
							  <td>NOM DU DIRIGEANT</td>
							  <td><select name="Identifiant_utilisateur">
								<?php
						do {  
						?>
								<option value="<?php echo $row_rs_user['Identifiant_utilisateur']?>"><?php echo $row_rs_user['Prenom_utilisateur']." ".$row_rs_user['Nom_utilisateur']?></option>
								<?php
						} while ($row_rs_user = mysql_fetch_assoc($rs_user));
						  $rows = mysql_num_rows($rs_user);
						  if($rows > 0) {
							  mysql_data_seek($rs_user, 0);
							  $row_rs_user = mysql_fetch_assoc($rs_user);
						  }
						?>
							  </select>      </td>
							</tr>
							<tr>
							  <td>REGION</td>
							  <td><select name="Identifiant_region">
								<?php
						do {  
						?>
								<option value="<?php echo $row_rs_reg1['Identifiant_region']?>"><?php echo $row_rs_reg1['Nom_region']?></option>
								<?php
						} while ($row_rs_reg1 = mysql_fetch_assoc($rs_reg1));
						  $rows = mysql_num_rows($rs_reg1);
						  if($rows > 0) {
							  mysql_data_seek($rs_reg1, 0);
							  $row_rs_reg1 = mysql_fetch_assoc($rs_reg1);
							  mysql_free_result($rs_reg1);
						  }
						?>
							  </select>      
							  </td>
							</tr>
						  </table>
					</div>
			</div>
			<div class="imgright"></div>				
				<div class="cleared"></div>
				
					<div class="bt1"><a href="<?php echo $retour; ?>"><span class="btleft"></span><span class="btmiddle">Retour</span><span class="btright"></span></a></div>
					<div class="bt"><span class="btleft"></span><input type="submit" name="Creer" value="Créer" class="resizeall btmiddle"/><span class="btright"></span></div>
					
				<div class="cleared"></div>
  <input type="hidden" name="Identifiant_unite" value="" />
  <input type="hidden" name="Etat_unite" value="A" />
  <input type="hidden" name="MM_insert" value="form1" />
</form>
</div>
</body>
</html>
<?php
mysql_free_result($rs);
mysql_free_result($rs_reg);
mysql_free_result($rs_user);
 ob_end_flush();?>